package com.woniu.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.Session;
import com.woniu.been.entity.Courses;
import com.woniu.been.entity.UserOrders;
import com.woniu.been.entity.Users;
import com.woniu.been.entity.vo.UserOrdersVo;
import com.woniu.mapper.UserOrdersMapper;
import com.woniu.service.UserOrdersService;

import com.woniu.utils.IDUtils;
import com.woniu.utils.PageResult;

import com.woniu.utils.RedisUtil;
import jakarta.transaction.Transactional;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
//@Transactional
public class UserOrdersServiceImpl implements UserOrdersService {

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private UserOrdersMapper userOrdersMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    @Tool(description = "查看订单列表")
    public  List<UserOrders> findAll(@ToolParam(description = "订单实体类") UserOrders userOrders) {
        return userOrdersMapper.findAll(userOrders);
    }

    /** 支付订单*/
//    必传 订单 id userid  已完成状态  修改时间
    @Override
    public String payOrder(UserOrders userOrders) {
       String lockKey = "course:purchase:" + userOrders.getUserId() + ":" + userOrders.getCourseId();
       String lockValue = IDUtils.randomId();
       if(redisUtil.delete(lockKey)){
           // 课程价格
           //Double price = userOrders.getPaymentAmount();
           //Users users = userOrdersMapper.findUserById(userOrders.getUserId());
           //if ( users.getMoney()-price >=0){
               //users.setMoney(users.getMoney()-price);


               userOrdersMapper.updateById(userOrders);
               //插入用户和课程信息 此表用来记录用户购买的课程
               userOrdersMapper.insertUserAndCourses(userOrders);
           //}else {
               //redisUtil.setIfAbsent(lockKey, lockValue, 15, TimeUnit.MINUTES);
              // return "余额不足，请充值！";
          // }
       }else {
           return "您已经下单过该课程，请勿重复购买！";
       }
       return "支付成功！";

    }

    @Override
    public PageResult QueryOrdersByPagination(UserOrdersVo userOrdersVo, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<UserOrders> list = userOrdersMapper.QueryOrdersByPagination(userOrdersVo);
        PageInfo<UserOrders> pageInfo = new PageInfo<>(list);
        PageResult ps = new PageResult(pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal(), pageInfo.getList());
        return ps;
    }
    /**
     * 通过订单号查询订单
     * @param orderNumber
     * @return
     */
    @Override
    public List<UserOrders> findOrderByNumber(String orderNumber) {
        return userOrdersMapper.findOrderByNumber(orderNumber);
    }
    /**
     * 通过订单号更新订单
     * @param orderNumber
     */
    @Override
    public void updateByNumber(String orderNumber) {
         userOrdersMapper.updateByNumber(orderNumber);
    }

    @Override
    public UserOrders findNumberByCourseId(Integer courseId,Integer userId) {
        return userOrdersMapper.findNumberByCourseId(courseId,userId);
    }


    /** 下订单*/
    @Override
    public String insertOrder(UserOrders userOrders) {


        String lockKey = "course:purchase:" + userOrders.getUserId() + ":" + userOrders.getCourseId();
        String lockValue = IDUtils.randomId();
        boolean lockAcquired = redisUtil.setIfAbsent(lockKey, lockValue, 15, TimeUnit.MINUTES);
        if (!lockAcquired) {

            return "您已经下单过该课程，请勿重复购买！";
        }
        try {
            userOrdersMapper.insertOrder(userOrders);
            rabbitTemplate.convertAndSend(
                    "delay.exchange",  // 业务交换机
                    "delay",           // 路由键
                    userOrders,      // 消息内容
                    message -> {
                        // 设置消息TTL为15（30000毫秒）
                        message.getMessageProperties().setExpiration("900000 ");
                        return message;
                    }
            );
            return "下单成功";
        }finally {
            // 释放锁
//            if (lockValue.equals(redisUtil.get(lockKey))) {
//                redisUtil.delete(lockKey);
//            }
        }

    }

    @Override
    public int updateById(UserOrders userOrders) {
      return   userOrdersMapper.updateById(userOrders);
    }

    @Override
    public void delById(String order_id) {
        userOrdersMapper.delById(order_id);
    }
    /** 批量删除*/
    @Override
    public void deleteBacthed(String ids) {
        //分割字符串
        String[] arr = ids.split(",");
        //遍历数组
        for(String id : arr){
            userOrdersMapper.delById(id);
        }
    }


    @Override
    public Double averageOrderPrice() {
        return userOrdersMapper.averageOrderPrice();
    }

    @Override
    public Double totalSales() {
        return userOrdersMapper.totalSales();
    }

    @Override
    public Integer totalOrders() {
        return userOrdersMapper.totalOrders();
    }

    @Override
    public List<Courses> courseSalesRanking() {
        return userOrdersMapper.courseSalesRanking();
    }

    @Override
    public List<Courses> courseSalesRankingByIncome() {
        return userOrdersMapper.courseSalesRankingByIncome();
    }

}
